package com.plr.fix;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Iterator;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;

public class FixExtract {

	static Splitter sp = Splitter.on('\t');
	static Joiner j = Joiner.on('\t');

	public static void main(String[] args) {

		File f = new File("ProfileDataExtract.txt");

		ArrayList<String> headers = new ArrayList<>();

		int profileDataIdx = -1;

		try (FileReader fr = new FileReader(f);
				BufferedReader reader = new BufferedReader(fr);

		) {

			String line = null;
			int i = 0;
			while ((line = reader.readLine()) != null) {

				if (i == 0) {
					profileDataIdx = 0;
					for (String h : sp.split(line)) {

						if ("ProfileData".equals(h)) {
							break;
						}
						profileDataIdx++;
						headers.add(h);

					}
				} else {
					Iterator<String> it = sp.split(line).iterator();
					String xml = null;
					for (int g = 0; g <= profileDataIdx && it.hasNext(); g++) {

						 xml = it.next();
					}
					
					System.out.println(xml);
				}

				i++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println(headers);
		System.out.println(profileDataIdx);

		try (FileReader fr = new FileReader(f);
				BufferedReader reader = new BufferedReader(fr);

				BufferedWriter writer = Files.newBufferedWriter(

				FileSystems.getDefault().getPath(".", "plr.txt"),
						Charset.forName("UTF-8"), StandardOpenOption.CREATE);

		) {

			String line = null;
			int i = 0;
			while ((line = reader.readLine()) != null) {

				if (i == 0) {
					profileDataIdx = 0;
					for (String h : sp.split(line)) {

						if ("ProfileData".equals(h)) {
							break;
						}
						profileDataIdx++;
						headers.add(h);

					}
				}
				Iterator<String> it = sp.split(line).iterator();

				writer.append(j.join(it));
				i++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
